﻿using MediatR;
using SmartMedicalCare.API.Read.Applications.Commands.科室;
using SmartMedicalCare.Domain;
using SmartMedicalCare.ErronCode;
using SmartMedicalCare.Infrastructure.Implaction;

namespace SmartMedicalCare.API.Read.Applications.CommandHandlers.科室
{
    public class QueryDepartmentTowCommandHandler : IRequestHandler<QueryDepartmentTowCommand, APIResult<APIPaging<DeptSubCategoryModel>>>
    {
        private readonly IBaseRespository<DeptSubCategoryModel> depRep;

        public QueryDepartmentTowCommandHandler(IBaseRespository<DeptSubCategoryModel> depRep)
        {
            this.depRep = depRep;
        }
        public Task<APIResult<APIPaging<DeptSubCategoryModel>>> Handle(QueryDepartmentTowCommand request, CancellationToken cancellationToken)
        {
            APIResult<APIPaging<DeptSubCategoryModel>> result = new APIResult<APIPaging<DeptSubCategoryModel>>();
            result.code = ResultCode.显示成功;
            result.Message = ResultCode.显示成功.ToString();

            var res = from a in depRep.GetAll()
                      where !a.IsDeleted && a.DepartmentId==request.DepartmentId
                      select new DeptSubCategoryModel
                      {
                          DeptSubCategoryId=a.DeptSubCategoryId,
                          Css=a.Css,
                          DepartmentId = a.DepartmentId,
                          Name = a.Name,
                          Intro = a.Intro,
                          Status = a.Status,
                          CreateTime = a.CreateTime,
                          IsDeleted = a.IsDeleted,
                          CreateName = a.CreateName,
                      };
            //总条数
            var totalcount = res.Count();
            //总页数
            var totalpage = (int)Math.Ceiling(totalcount * 1.0 / request.Pagsize);
            //排序
            res = res.OrderByDescending(x => x.DepartmentId).Skip((request.Pagindex - 1) * request.Pagsize).Take(request.Pagsize);

            APIPaging<DeptSubCategoryModel> paging = new APIPaging<DeptSubCategoryModel>();
            paging.totalCount = totalcount;
            paging.totalPage = totalpage;
            paging.Fdata = res.ToList();
            result.Data = paging;
            return Task.FromResult(result);
        }
    }
}
